package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.autoconfig.template.HuanXinTemplate;
import com.tanhua.dubbo.api.CommentApi;
import com.tanhua.dubbo.api.FriendApi;
import com.tanhua.dubbo.api.UserApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.domain.User;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.dto.RecommendUserDto;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.mongo.Friend;
import com.tanhua.model.vo.*;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Author: cl
 * @Date: 2022/5/7 - 05 - 07
 * @Description:
 */

/**
 * 环信消息模块
 */
@Service
public class MessagesService {

    //用户信息服务
    @DubboReference
    private UserInfoApi userInfoApi;

    //用户服务
    @DubboReference
    private UserApi userApi;

    //好友服务
    @DubboReference
    private FriendApi friendApi;

    //环信
    @Autowired
    private HuanXinTemplate huanXinTemplate;

    @DubboReference
    private CommentApi commentApi;

    /**
     * 通过环信的id查询用户的信息
     *
     * @param huanxinId
     * @return
     */
    public UserInfoVo getUserinfo(String huanxinId) {

        //1、通过环信id查询user表获取用户id
        User user = userApi.findByHuanXinId(huanxinId);
        //2、判断是否有用户
        if (user == null) {
            throw new BusinessException(ErrorResult.error());
        }
        //3、通过用户id查询用户信息
        UserInfo userInfo = userInfoApi.findById(user.getId());
        //4、封装vo返回
        UserInfoVo userInfoVo = new UserInfoVo();
        BeanUtils.copyProperties(userInfo, userInfoVo);
        if (userInfo.getAge() != null) {
            userInfoVo.setAge(userInfo.getAge().toString());
        }
        return userInfoVo;
    }

    /**
     * 通过被添加人的id添加好友
     *
     * @param friendId
     */
    public void contacts(Long friendId) {

        //1、获取用户的id
        Long userId = UserHolder.getUserId();
        //2、添加好友到环信
        Boolean b = huanXinTemplate.addContact("hx" + userId.toString(), "hx" + friendId.toString());
        if (!b) {
            throw new BusinessException(ErrorResult.error());//添加不成功抛出异常
        }
        //3、添加好友到好友表
        friendApi.contacts(userId, friendId);
    }

    /**
     * 通过id删除好友
     *
     * @param friendId
     */
    public void delete(Long friendId) {

        //1、获取用户的id
        Long userId = UserHolder.getUserId();
        //2、删除数据库
        boolean b = friendApi.delete(UserHolder.getUserId(), friendId);
        if (!b) {
            throw new BusinessException(ErrorResult.error());//添加不成功抛出异常
        }
        //3、删除环信好友
        huanXinTemplate.deleteContact("hx" + userId.toString(), "hx" + friendId.toString());
    }

    /**
     * 分页展示好友列表(通过好友名字条件查询)
     *
     * @param page
     * @param pagesize
     * @param keyword
     * @return
     */
    public PageResult getFriend(Integer page, Integer pagesize, String keyword) {
        //1、获取用户id
        Long userId = UserHolder.getUserId();
        List<Friend> list = new ArrayList<>();
        //2、判断是否有条件
        if (StringUtils.isEmpty(keyword)) {
            //2.1没条件分页查询好友关系
            list = friendApi.findByUserId(page, pagesize, userId);
        } else {
            //2.2有条件查询所有还有关系
            list = friendApi.findAllByUserId(userId);
        }

        //3、判断是否有数据
        if (CollUtil.isEmpty(list)) {
            return new PageResult();
        }
        //4、如果有信息调用用户信息服务查询用户信息
        //获取用户ids
        List<Long> ids = CollUtil.getFieldValues(list, "friendId", Long.class);
        //创建条件
        RecommendUserDto recommendUserDto = new RecommendUserDto();
        recommendUserDto.setNickname(keyword);
        Map<Long, UserInfo> map = userInfoApi.selectByIds(ids, recommendUserDto);
        //5、封装vo对象
        List<ContactVo> vos = new ArrayList<>();
        for (Friend friend : list) {
            //判断是否有用户信息，有信息再封装
            if (map.get(friend.getFriendId()) != null) {
                ContactVo vo = ContactVo.init(map.get(friend.getFriendId()));
                vos.add(vo);
            }
        }
        return new PageResult(page, pagesize, 0l, vos);
    }

    /**
     * 点赞列表
     *
     * @param page
     * @param pagesize
     * @return
     */
    public PageResult likes(Integer page, Integer pagesize) {
        return get(page, pagesize, 1);
    }

    /**
     * 评论列表
     *
     * @param page
     * @param pagesize
     * @return
     */
    public PageResult comments(Integer page, Integer pagesize) {

        return get(page, pagesize, 2);

    }

    private PageResult get(Integer page, Integer pagesize, Integer type) {
        List<Comment> list = commentApi.getByPublishUserIdAndType(UserHolder.getUserId(), type, page, pagesize);

        List<CommentVo> vos = new ArrayList<>();
        if (!list.isEmpty()) {
            List<Long> userId = CollUtil.getFieldValues(list, "userId", Long.class);
            Map<Long, UserInfo> map = userInfoApi.selectByIds(userId, new RecommendUserDto());

            for (Comment comment : list) {
                UserInfo userInfo = map.get(comment.getUserId());
                if (userInfo != null) {
                    CommentVo init = CommentVo.init(userInfo, comment);
                    vos.add(init);
                }
            }
        }
        return new PageResult(page, pagesize, 0l, vos);
    }

    /**
     * 喜欢列表
     *
     * @param page
     * @param pagesize
     * @return
     */
    public PageResult loves(Integer page, Integer pagesize) {
        return get(page, pagesize, 3);
    }
}
